<template>
  <div class="myVideo">
    <video class="myVideo" ref="vedioEle"  muted width="200"></video>
  </div>
</template>
 
<script>
// 安装依赖: npm install hls.js
import Hls from 'hls.js'
export default {
    props:{
        url:{
          type: String,
          default:'',
        }
    },
  data() {
    return {
      hls:null, // hls实例
      video: null,
      timer:null
    }
  },
  created() {},
  watch: {
    url: {
      immediate: false,
      handler(newVal) {
        if (newVal) {
			console.log(newVal,"newVal");
          this.initializePlayer();
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initializePlayer()
    })
  },
  beforeUnmount() {},
 
  methods: {
    initializePlayer() {
      this.video = this.$refs.vedioEle;
      if (!this.url) {
        // 如果url为空，显示加载提示
        this.showLoadingIndicator();
        return;
      }
      this.hlsPlay();
    },
    showLoadingIndicator() {
      // 显示加载提示的逻辑
      // 这里可以是修改DOM，或者显示一个加载动画等
      console.log('正在加载视频...');
      // 您可能需要添加一些逻辑来定时检查url是否已经赋值
      // 如果赋值了，就调用this.hlsPlay()来开始播放
    },
    hlsPlay() {
      this.video = this.$refs.vedioEle

      if (Hls.isSupported()) {
        console.log('__________________________-',);
        //如果支持hLs.js (MediaSource Extensions)
        this.hls = new Hls()
        this.hls.loadSource(this.url)
        this.hls.attachMedia(this.video)
        this.hls.on(Hls.Events.BUFFERING, (event, data) => {
          console.log('缓冲中...');
        });
        this.hls.on(Hls.Events.MANIFEST_LOADED, (event, data) => {
          console.log('播放列表已更新，尝试恢复播放');
          if (!this.video.paused) {
            this.video.play();
          }
        });
        //自动播放
        this.hls.on(Hls.Events.MANIFEST_PARSED,  (event, data) =>  {
          this.timer = setTimeout(() => {
            this.video.play()
          },500);
        })
      } else if (this.video.canPlayType('application/vnd.apple.mpegurl')) {
        //如果支持原生播放
        this.video.src = this.url
        //自动播放
        this.video.addEventListener('canplay', () => {
          this.timer = setTimeout(() => {
            this.video.play()
          },500);
        });
      }
    }
  },
  beforeDestroy() {
    if (this.hls) {
      this.hls.destroy();
    }
    clearTimeout(this.timer);
  }
}
</script>
 
<style>
.myVideo {
  width: 100%;
  height: 100%;
}
</style>